from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt, QString
from .msg_cell import MsgCell

class MsgMain(QtGui.QWidget):
        def __init__(self, *args, **kw):
		QtGui.QWidget.__init__(self, *args, **kw)
		self.setGeometry(0,0,715,564)

		bg = QtGui.QLabel(self)
		path = "resources/msg_main.png"
		bg.setPixmap(QtGui.QPixmap(path))
		bg.move(0,0)

		self.image = QtGui.QLabel(self)
		self.image.setGeometry(136,20,553,422)
		self.image.setAlignment(Qt.AlignVCenter|Qt.AlignHCenter)
		self.img_x = 553
		self.img_y = 422

		self.events = []
		self.cells = []
		self.current = None

		for i in range(20):
			cell = MsgCell(self)
			cell.move(20,25 + i * 26 )
			cell.set_time(2310)
			self.cells.append(cell)
			cell.hide()
			cell.index = i
			cell.clicked.connect(self.clicker)

		self.narrative = QtGui.QLabel(self)
		self.narrative.setGeometry(150,467,530,79)
		self.narrative.setWordWrap(1==1);

	def set_text(self, s):
		self.narrative.setText(s)

	def set_image(self, path):
		pix = QtGui.QPixmap(path)
		px2 = pix.scaled(
			self.img_x,
			self.img_y,
			Qt.KeepAspectRatio,
			Qt.SmoothTransformation
		)
		self.image.setPixmap(px2)

	def set_events(self, events):
		for cell in self.cells:
			cell.hide()
		self.events = events
		for i, e in enumerate(self.events):
			cell = self.cells[i]
			cell.set_time(e.time)
			cell.show()
			print e
			cell.ev = e
			print "setting: ", i, ":", cell.ev

	def clicker(self, cell, state):
		print "clicker"
		if state == False:
			return
		for c in self.cells:
			if c == cell:
				continue
			c.set_toggle_state(False)
		e = cell.ev
		print e
		self.set_image(e.image)
		self.set_text(e.description)

if __name__ == "__main__":
	import sys, random
	from glob import glob

	#
	# Nice trick! Thanks, slate!
	#
	class Event:
		def __init__(self, **kw):
			self.__dict__.update(kw)
		def __str__(self):
			return "Event: {} - {}".format(
				self.time, self.description
			)

	app = QtGui.QApplication(sys.argv)

	ll = glob("resources/characters/Black Widow/*")

	frame = None
	def reroll():
		frame.set_image(random.choice(ll))

	font_db = QtGui.QFontDatabase()
	font_db.addApplicationFont("resources/Gabrielle.ttf")
#
#	use the wallpaper as the top level widget
#
	top = QtGui.QLabel()
	top.setGeometry(0, 0, 1024, 768)
	path = "resources/wood.jpg"
	top.setPixmap(QtGui.QPixmap(path))

	Seq = QtGui.QKeySequence
	Shorty = QtGui.QShortcut
	Shorty(Seq(Qt.Key_R), top, reroll)

	frame = MsgMain(top)
	frame.move(20,20)
	reroll()
	frame.set_events([
		Event(	time = 120,
			description = "This is a test description. Kindly take it as read that a lot of stuff happened and that it was all very interesting.",
			image = random.choice(ll)
		),
		Event(	time = 150,
			description = "then some more stuff happened",
			image = random.choice(ll)
		),
		Event(	time = 240,
			description = "then some stuff after that",
			image = random.choice(ll)
		)
	])

	top.show()
	sys.exit(app.exec_())
